// tools/scripts/kill-ports.js
import { execSync } from 'child_process';
import { promisify } from 'util';

const ports = [3000, 5001, 5002, 5003, 5004, 3001];

function killPort(port) {
  try {
    if (process.platform === 'win32') {
      // Windows
      execSync(`npx kill-port ${port}`, { stdio: 'inherit' });
    } else {
      // macOS/Linux
      const result = execSync(`lsof -ti:${port}`, { encoding: 'utf-8' });
      const pids = result.trim().split('\n').filter(pid => pid);
      
      if (pids.length > 0) {
        console.log(`🛑 杀死端口 ${port} 的进程: ${pids.join(', ')}`);
        execSync(`kill -9 ${pids.join(' ')}`);
      } else {
        console.log(`✅ 端口 ${port} 没有被占用`);
      }
    }
  } catch (error) {
    // 如果没有进程占用端口，会抛出错误，这是正常的
    if (!error.message.includes('No such process')) {
      console.log(`✅ 端口 ${port} 没有被占用`);
    }
  }
}

console.log('🧹 清理端口占用...\n');

ports.forEach(port => {
  console.log(`处理端口 ${port}...`);
  killPort(port);
});

console.log('\n🎉 端口清理完成！');